<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>Happy ERP</title>

    <script type="text/javascript">
      var newProductWin;
      var editProductWin;
      var currentNode;
      var currentPage = 1;
      var psPageSize = 25 //product setup pagesize
      var totalCount = <%=@totalCount%>;
      var totalPage = 0;
      var tree;
      var searchKey = null; //用来确认一下，是不是
      Ext.onReady(function(){
        function pageBtnDisable(){
          Ext.getCmp('pfid').disable();
          Ext.getCmp('pvid').disable();
          Ext.getCmp('pnid').disable();
          Ext.getCmp('plid').disable();

        }
        function pageBtnEnable(){
          Ext.getCmp('pfid').enable();
          Ext.getCmp('pvid').enable();
          Ext.getCmp('pnid').enable();
          Ext.getCmp('plid').enable();
        }
        //这是跳页函数
        function paging(i){
          currentPage = i;
          if (i < 0) {currentPage = 1;}
          totalPage = (totalCount % psPageSize) > 0 ? Math.floor(totalCount/psPageSize) + 1 : Math.floor(totalCount/psPageSize);
          if(currentPage > totalPage){currentPage = totalPage;}
          pageBtnDisable();
          Ext.getCmp('pageNumber').setValue(currentPage);
          dateReload(currentPage);
        }

        //导入相应页数的数据
        function dateReload(currentPage){
          Ext.Ajax.request({
            url : '/product/getProductCount?'+searchKey,
            success : function(response) {
              totalCount = parseInt(response.responseText);
              if (searchKey == null){
                tree.loader.dataUrl='/product/getTreeData?start='+ (currentPage==1?0:(currentPage-1)*psPageSize-1) +'&limit='+psPageSize;
              }else{
                tree.loader.dataUrl='/product/getTreeData?start='+ (currentPage==1?0:(currentPage-1)*psPageSize-1) +'&limit='+psPageSize+"&"+searchKey;
              }              
              tree.loader.load(tree.root,null);
              tree.root.expand();
              refreshPageInfo();
              pageBtnEnable();
            },
            failure : function() {
              Ext.Msg.alert("提示", "连接数据库错误或连接超时！")
              pageBtnEnable();
            }
          });
        }
 
        Ext.Msg.getDialog().setWidth(400);
        var pageSubInfo = new Ext.Toolbar.TextItem("&nbsp;页 , 共 "+((totalCount % psPageSize) > 0 ? Math.floor(totalCount/psPageSize) + 1 : Math.floor(totalCount/psPageSize)) +' 页');
        var pageTotalInfo = new Ext.Toolbar.TextItem('显示第 ' + ((currentPage-1)*psPageSize > 0 ? Math.floor(currentPage/psPageSize):1) + '  条到 '+currentPage*psPageSize + ' 条记录，一共 '+totalCount+' 条');
        
        function refreshPageInfo(){
          pageSubInfo.setText("&nbsp;页 , 共 "+((totalCount % psPageSize) > 0 ? Math.floor(totalCount/psPageSize) + 1 : Math.floor(totalCount/psPageSize)) +' 页');
          //判断是不是最后一页
          if (currentPage == (Math.floor(totalCount/psPageSize) + 1)){
            pageTotalInfo.setText('显示第 ' + ((currentPage-1)*psPageSize > 0 ? Math.floor(currentPage-1)*psPageSize : 1) + '  条到 '+totalCount + ' 条记录，一共 '+totalCount+' 条');
          }else{
            pageTotalInfo.setText('显示第 ' + ((currentPage-1)*psPageSize > 0 ? Math.floor(currentPage-1)*psPageSize : 1) + '  条到 '+currentPage*psPageSize + ' 条记录，一共 '+totalCount+' 条');
          }
          
        }
        
        tree = new Ext.tree.ColumnTree({
          width: screenWidth-190,
          height: 600,
          rootVisible:true,
          autoScroll:true,
          title: '树形产品列表',
          //renderTo: 'products_tree_div',
          columns:[{
              header:'名称',
              width:280,
              dataIndex:'id'
            },{
              header:'品牌',
              width:70,
              dataIndex:'brand_name'
            },{
              header:'编号',
              width:130,
              dataIndex:'number'
            },{
              header:'类型',
              width:80,
              dataIndex:'product_type'
            },{
              header:'规格',
              width:80,
              dataIndex:'spec'
            },{
              header:'销售单价',
              width:70,
              align: 'right',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              dataIndex:'unit_price'
            },{
              header:'数量',
              align: 'right',
              width:60,
              dataIndex:'quantity'
            },{
              header:'备注',
              width:260,
              dataIndex:'description'
            },{
              header: '生成日期',
              dataIndex: 'created_at',
              width: 105
            },{
              header: '修改日期',
              dataIndex: 'updated_at',
              width: 105
            }],

          loader: new Ext.tree.TreeLoader({
            dataUrl:'/product/getTreeData?start=0&limit='+psPageSize,
            uiProviders:{
              'col': Ext.tree.ColumnNodeUI
            }
          }),

          root: new Ext.tree.AsyncTreeNode({
            id:0,
            text:'Products'
          }),
          bbar: [{
              id: 'pfid',
              tooltip: '第一页',
              iconCls:'page-first',
              listeners: {
                'click': function() {
                  currentPage = 1;            
                  paging(currentPage);                  
                }
              }
            },{
              id: 'pvid',
              tooltip: '上一页',
              iconCls:'page-prev',
              listeners: {
                'click': function() {
                  if (currentPage>1){
                    currentPage = currentPage - 1;
                    paging(currentPage);
                  }                  
                }
              }
            },'-',new Ext.Toolbar.TextItem('第 '),{
              id: 'pageNumber',
              xtype: 'numberfield',
              emptyText: currentPage > 1 ? currentPage : 1,
              //data: 6,
              enableKeyEvents: true,
              decimalPrecision:0,
              allowNegative: false,
              allowDecimals: false,
              style:'color:#000;',
              selectOnFocus: true,
              width: 30,
              listeners: {
                keypress: function(obj, evt){
                  if (evt.getKey() == Ext.EventObject.RETURN){
                    currentPage = this.getValue()
                    paging(currentPage);
                  }
                }
              }
            },pageSubInfo,
            '-',{
              id: 'pnid',
              tooltip: '下一页',
              iconCls:'page-next',
              listeners: {
                'click': function() {
                  paging(currentPage + 1);
                }
              }
            },{
              id: 'plid',
              tooltip: '最后页',
              iconCls:'page-last',
              listeners: {
                'click': function() {
                  currentPage = ((totalCount % psPageSize) > 0 ? Math.floor(totalCount/psPageSize) + 1 : Math.floor(totalCount/psPageSize))
                  paging(currentPage);
                }
              }
            },'->',
            pageTotalInfo]

        });

        tree.on("contextmenu",function(node,e){
          e.preventDefault();
          productRightMenu.showAt(e.getXY());
          //productRightMenu.show(node.ui.getAnchor());
          node.select();
          currentNode = node;
          nodeId = currentNode.id;
          //window.status = currentNode.id;
          //alert(typeof(currentNode.id)==="string");
          //如果为叶子，则禁止刷新功能。
          if (node.isLeaf()){
            refreshMenuItem.setDisabled(true);
            addProductMenuItem.setDisabled(true);
          }else{
            //检查是不是根节点，只有根节点才具有添加产品的功能，
            if (nodeId == 0){
              addProductMenuItem.setDisabled(false);
              editProductMenuItem.setDisabled(true);
              delProductMenuItem.setDisabled(true);
            }else{
              addProductMenuItem.setDisabled(true);
            }
            refreshMenuItem.setDisabled(false);
          }
          //如果不是根上的叶或节点，禁止修改编辑,string为非根节点上的直接叶或节点。
          if (typeof(currentNode.id)==="string"){
            editProductMenuItem.setDisabled(true);
            delProductMenuItem.setDisabled(true);
          }else if (typeof(currentNode.id)==="number" && nodeId != 0){
            editProductMenuItem.setDisabled(false);
            delProductMenuItem.setDisabled(false);
          }
        },this);
        
        //右键菜单
        var addProductMenuItem = new Ext.menu.Item({
          text: '添加产品或套装',
          iconCls: 'addItem',
          handler: rightMenuProductTreeFn
        });
        var editProductMenuItem = new Ext.menu.Item({
          text: '编辑产品或套装',
          iconCls: 'editItem',
          handler: rightMenuProductTreeFn
        });
        var delProductMenuItem = new Ext.menu.Item({
          text: '删除',
          iconCls: 'remove',
          handler: rightMenuProductTreeFn
        });
        var refreshMenuItem = new Ext.menu.Item({
          text: '刷新',
          iconCls: 'refresh',
          handler: rightMenuProductTreeFn
        });
        
        var productRightMenu = new Ext.menu.Menu({
          //id: 'product_right_menu',
          items: [
            addProductMenuItem,
            editProductMenuItem,
            '-',
            delProductMenuItem,
            '-',
            refreshMenuItem
          ]});
        function rightMenuProductTreeFn(item,e){
          if (item.text=="添加产品或套装"){
            newProductWin = new Ext.Window({
              layout: 'fit',
              width: 860,
              height: 630,
              closeAction: 'destroy',
              plain: true,
              modal: true,
              constrain:true,
              //modal: true,
              title: '添加产品或套装',
              autoLoad: {
                url: "/product/newProduct",
                scripts: true
              }
            });
            newProductWin.on("destroy",function(){
              //刷新整个树
              //tree.root.reload();
            });
            newProductWin.resizable = false;
            newProductWin.show();
          }else if (item.text=="编辑产品或套装"){
            editProductWin = new Ext.Window({
              layout: 'fit',
              width: 860,
              height: 620,
              closeAction: 'destroy',
              plain: true,
              modal: true,
              constrain:true,
              //modal: true,
              title: '编辑产品或套装',
              autoLoad: {
                url: "/product/editProduct?id=" + currentNode.id,
                scripts: true
              }
            });
            editProductWin.on("destroy",function(){
              //刷新整个树
              //tree.root.reload();
            });
            editProductWin.resizable = false;
            editProductWin.show();
          }else if (item.text=="刷新"){
            if (currentNode.isLeaf()){
              alert("是一个Child");
            }else{
              //判断是否导入过，就是是否被人点击过，因为这是Ajax的，一但点击，就会导入数据。
              if (currentNode.isLoaded()){
                //如果导入过，就要刷新后，再expand();
                tree.loader.dataUrl = "/product/getTreeData?node=" + currentNode.id; //定义子节点的Loader
                tree.loader.load(currentNode,expandCurrentNode);
                tree.root.expand();
              }else{
                //如果没有导入过，触发expand事件，就可以导入，相当于刷新。
                currentNode.expand();
              }
              //tree.getRootNode().select();
              window.state = currentNode.id;
              //currentNode.reload();
            }
          }else if(item.text == "删除"){
            Ext.MessageBox.confirm("提示","你确认删除 \""+currentNode.text+"\" 吗？",function(btn){
              if(btn=="yes"){
                Ext.Ajax.request({
                  url : '/product/destroy?id=' + currentNode.id,
                  success : function (result, request) {
                    tree.root.reload();
                  },
                  failure : function (result, request){
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "通讯失败，请从新操作",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  },
                  method : 'GET'
                });
              }else{
                //alert("no");
              }
            });
          }
        }
        
        function expandCurrentNode(){
          //alert(currentNode.id);
          currentNode.expand();
          //currentNode.cascade();
        }
        
        
        tree.on('beforeload',
        function(node){
          tree.loader.dataUrl='/product/getTreeData?node='+node.id+'&start=0&limit='+psPageSize; //定义子节点的Loader
        });
        tree.root.id = 0;
        tree.root.expand();
        //tree.render();

        var productName = new Ext.form.TextField({
          fieldLabel: '产品名称或编号',
          name: 'name',
          anchor: '95%'
        });

        //产品类型相关combobox
        var productTypeTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        var productTypeStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/product_type/getAllProductTypes?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }])
        });

        //产品类型
        var productType = new Ext.form.ComboBox({
          store: productTypeStore,
          fieldLabel: '产品类别',
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'product_type_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          readOnly:false,
          tpl: productTypeTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });


        //品牌相关combobox
        var brandTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        var brandStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/brand/getAllBrands?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }])
        });

        //品牌
        var brand = new Ext.form.ComboBox({
          store: brandStore,
          fieldLabel: '品牌',
          allowBlank: false,
          blankText: "品牌必须选择",
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'brand_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          editable:false,
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '95%',
          readOnly:false,
          tpl: brandTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        var searchButton = new Ext.Button({
          text: '搜索',
          iconCls: 'finding',
          width:70,
          handler: function(){
            searchKey = 'name=' + encodeURIComponent(productName.getValue());
            if (productType.getValue() != ''){
              searchKey = searchKey + "&product_type_id=" + productType.getValue();
            }
            if (brand.getValue() != ''){
              searchKey = searchKey + "&brand_id=" + brand.getValue();
            }
            paging(1);
          }
        });

        var clearButton = new Ext.Button({
          text: '清空',
          width:50,
          handler: function(){
            queryFormPanel.form.reset();
            searchKey = null;
          }
        });
        
        var queryFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'query_form',
          labelWidth: 95,
          width: screenWidth-175,
          labelAlign: 'right',
          frame : true,
          border:false,
          items: [{
              xtype: 'fieldset',
              defaults: {width: screenWidth-190},
              title: '查询条件',
              border: true,
              items: [{
                  layout: 'column',
                  border: false,
                  items: [{
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [productName]
                    },{
                      columnWidth: .16,
                      layout: 'form',
                      border: false,
                      labelWidth: 60,
                      items: [productType]
                    },{
                      columnWidth: .16,
                      layout: 'form',
                      border: false,
                      labelWidth: 60,
                      items: [brand]
                    }, {
                      columnWidth: .1,
                      layout: 'form',
                      border: false,
                      items: [searchButton]
                    }, {
                      columnWidth: .2,
                      layout: 'form',
                      border: false,
                      items: [clearButton]
                    }]
                }]
            }]
        });
        
        //总的panel
        var workbenchPanel = new Ext.Panel({
          width: screenWidth-175,
          height: 700,
          //html: '&lt;empty panel&gt;',
          //cls:'cellpadding:10',
          /*layout: {
            type:'vbox',
            align:'stretch'
          },*/
          frame:false,
          layout:'table',
          layoutConfig: {columns:1},
          defaults:{margins:'5 5 5 5'},
          //bodyStyle: 'padding:15px;align:center',
          //listeners: {
          //expand: showAgileDiagram
          //},
          items:[queryFormPanel,tree]
        });
        workbenchPanel.render("products_div");        
      });
    </script>
  </head>
  <body>    
    <div id="products_div"></div>
  </body>
</html>
